package user

import (
	"context"
	"gitee.com/bobo-rs/innovideo-services/enums"
	"gitee.com/bobo-rs/innovideo-services/framework/model"
	"gitee.com/bobo-rs/innovideo-services/framework/model/entity"
	"gitee.com/bobo-rs/innovideo-services/framework/service"
	"gitee.com/bobo-rs/innovideo-services/library/exception"
	"gitee.com/bobo-rs/innovideo-services/library/services/email"
	"gitee.com/bobo-rs/innovideo-services/library/services/login"
)

// OauthEmailCaptchaLogin 用户认证邮箱验证码登录
func (u *sUser) OauthEmailCaptchaLogin(ctx context.Context, in model.UserOauthEmailCaptchaLogin) (detail *model.UserOauthLoginDetailItem, err error) {
	detail = &model.UserOauthLoginDetailItem{}
	// 邮箱验证码验证
	err = email.New().ValidatorCaptcha(ctx, in.Email, in.Code)
	if err != nil {
		return nil, exception.Newf(`邮箱验证码验证失败%s`, err.Error())
	}

	// 获取账户信息
	if err = u.QueryDetailByEmail(ctx, in.Email, &detail.User); err == nil && detail.User != nil {
		// 老用户，直接返回
		return detail, nil
	}

	// 手机号不存在，创建新用户
	newUserDetail := model.UserSaveUserDetailItem{
		User: &entity.User{
			Email: in.Email,
		},
	}
	if err = u.CreateOauthUser(ctx, &newUserDetail); err != nil {
		return nil, err
	}

	// 返回用户信息
	detail.User = newUserDetail.User
	detail.Status = enums.UserLoginStatusSP // 提醒未设置密码
	return
}

// OauthSendEmailCaptcha 用户认证发送邮箱验证码
func (u *sUser) OauthSendEmailCaptcha(ctx context.Context, in model.LoginSendEmailCaptchaInput) error {
	// 安全认证并解密
	item, err := service.Common().Verify(
		ctx, in.Sign, enums.SafeTagsEmailCaptcha, true,
	)
	if err != nil {
		return err
	}
	// 解密邮箱
	e, err := login.New().Decrypt(in.Email, item.Secret)
	if err != nil {
		return err
	}
	// 发送验证码
	return service.Email().SendCaptcha(ctx, e, `login-captcha`)
}
